﻿/*
 * @author: wizardc
 */

using System.IO;
using DouEditor.Const;
using DouEditor.Utils;
using UnityEditor;
using UnityEditor.U2D;
using UnityEngine.U2D;

namespace DouEditor.Resource
{
    /// <summary>
    /// 处理图集资源
    /// 会将指定路径下的零散小图按目录设定为图集，打包时请设定小图文件夹无需关注生成的图集文件。
    /// </summary>
    public class BuildStep_CreateAtlas : BuildStepBase
    {
        private const string Extension = ".spriteatlas";
        
        protected override void Start()
        {
            if (Directory.Exists(BuildConst.AtlasDefineFolder))
            {
                Directory.Delete(BuildConst.AtlasDefineFolder, true);
            }
            EditorUtil.CreateDir(BuildConst.AtlasDefineFolder);

            var dirs = Directory.GetDirectories(BuildConst.AtlasSpriteFolder);
            foreach (var dir in dirs)
            {
                var name = Path.GetFileNameWithoutExtension(dir);
                string atlasFilePath = Path.Combine(BuildConst.AtlasDefineFolder, name + Extension);
                
                var spriteAtlas = new SpriteAtlas();
                spriteAtlas.Add(new[]
                {
                    AssetDatabase.LoadAssetAtPath<UnityEngine.Object>(dir)
                });
                spriteAtlas.SetPackingSettings(new SpriteAtlasPackingSettings()
                {
                    enableRotation = false,
                    enableTightPacking = false,
                    padding = 4
                });
                
                var setting =  spriteAtlas.GetPlatformSettings("Android");
                setting.overridden = true;
                setting.format = TextureImporterFormat.ASTC_4x4;
                spriteAtlas.SetPlatformSettings(setting);
                
                setting =  spriteAtlas.GetPlatformSettings("iPhone");
                setting.overridden = true;
                setting.format = TextureImporterFormat.ASTC_4x4;
                spriteAtlas.SetPlatformSettings(setting);
                
                AssetDatabase.CreateAsset(spriteAtlas, atlasFilePath);
            }
            
            Complete();
        }
    }
}
